<template>
  <div class="competitiveness-wrapper">
    <div class="big-title">竞争力分析</div>
    <div class="top">
      <div class="chart-wrapper">
        <LineChart :data="echartsData" :visibleData="visibleData"></LineChart>
      </div>
      <div class="rank-wrapper">
        <div class="title">
          <span class="text">你的竞争力排名为</span>
          <span class="rank"> {{ '前' + rankPercentage + '%' }} </span>
        </div>
        <div class="analysis-box">
          <div class="header">
            <div>{{ volunteerInfo.score }}分历年排名分析</div>
            <div class="btn" @click="showScoreRangePopup = true">
              {{ volunteerInfo.searchRankYear }}年一分一段表
            </div>
          </div>
          <div class="table">
            <MyTable :data="tableData" :columns="columns" :isShowHeader="true">
              <template #maxRank="{ row }">
                {{ row.maxRank }} - {{ row.minRank }}
              </template>
            </MyTable>
          </div>
        </div>
      </div>
    </div>
    <div class="bottom">
      <div class="left">
        <div class="header">
          <div class="label">推荐分数区间</div>
          <div class="value">
            {{ +volunteerInfo.score - 70 }}-{{ +volunteerInfo.score + 30 }}分
          </div>
        </div>
        <div class="content">
          <div
            :class="['item', getClassname(item)]"
            v-for="item in recommendData"
            :key="item.label"
          >
            <div class="label">{{ item.label }}</div>
            <div class="value">{{ item.value }}</div>
          </div>
        </div>
      </div>
      <div class="right">
        <div class="content" v-if="cityData && cityData.length > 0">
          <PieChart :colors="colors" :data="cityData"></PieChart>
          <div class="title">志愿城市分布</div>
        </div>
        <div class="content" v-if="majorData && majorData.length > 0">
          <PieChart :colors="colors" :data="majorData"></PieChart>
          <div class="title">志愿类目分布</div>
        </div>
      </div>
    </div>
  </div>
  <ScoreRangePopup
    v-if="showScoreRangePopup"
    @close="showScoreRangePopup = false"
  ></ScoreRangePopup>
</template>
<script setup>
import { ref, onMounted, computed, watch } from 'vue';
import { useVolunteerStore } from '@/store/volunteer';
import LineChart from './LineChart.vue';
import PieChart from './PieChart.vue';
import MyTable from '@/components/MyTable.vue';
import ScoreRangePopup from './ScoreRangePopup.vue';
import {
  sameScoreList,
  getRushSteadyGroupNum,
  volunteerPercentage,
  competitivenessScore,
} from '@/api/volunteer';

const store = useVolunteerStore();
const volunteerInfo = computed(() => store.volunteerInfo);

const showScoreRangePopup = ref(false);
const rankPercentage = ref(0);

const columns = ref([
  {
    label: '年份',
    prop: 'recordYear',
  },
  {
    label: '同分人数',
    prop: 'segmentNum',
  },
  {
    label: '排名区间',
    prop: 'maxRank',
  },
]);

const tableData = ref([]);
const sameScoreListFn = async () => {
  const params = {
    localRegionId: volunteerInfo.value.regionId,
    minScore: volunteerInfo.value.score,
    subjectType: volunteerInfo.value.subjectType,
    orderBy: '20',
  };
  const res = await sameScoreList(params);
  if (res.code == 200) {
    tableData.value = res.data.slice(0, 4);
  }
};

const colors = ['#e2dcff', '#c2e1ff', '#ede4de', '#c9eeeb'];

const cityData = ref([]);
const volunteerPercentageByCityFn = async () => {
  const params = {
    localRegionId: volunteerInfo.value.regionId,
    userScore: volunteerInfo.value.score,
    userMinScore: +volunteerInfo.value.score - 70,
    userMaxScore: +volunteerInfo.value.score + 30,
    recordYear: volunteerInfo.value.defaultYear,
    subject: volunteerInfo.value.relSubject,
    searchAllowSubject: volunteerInfo.value.relSubject,
    subjectType: volunteerInfo.value.subjectType,
    groupByColumn: 'city_type',
    showPercentNum: '3',
  };
  const res = await volunteerPercentage(params);
  if (res.code == 200) {
    const temp = res.data.map((item) => {
      return {
        name: item.title,
        value: item.percentage,
      };
    });
    cityData.value = temp;
  }
};

const majorData = ref([]);
const volunteerPercentageByMajorFn = async () => {
  const params = {
    localRegionId: volunteerInfo.value.regionId,
    userScore: volunteerInfo.value.score,
    userMinScore: +volunteerInfo.value.score - 70,
    userMaxScore: +volunteerInfo.value.score + 30,
    recordYear: volunteerInfo.value.defaultYear,
    subject: volunteerInfo.value.relSubject,
    searchAllowSubject: volunteerInfo.value.relSubject,
    subjectType: volunteerInfo.value.subjectType,
    groupByColumn: 'major_category',
    showPercentNum: '4',
  };
  const res = await volunteerPercentage(params);
  if (res.code == 200) {
    const temp = res.data.map((item) => {
      return {
        name: item.title,
        value: item.percentage,
      };
    });
    majorData.value = temp;
  }
};

const recommendData = ref([
  {
    label: '冲',
    value: 0,
  },
  {
    label: '稳',
    value: 0,
  },
  {
    label: '保',
    value: 0,
  },
]);
const getRushSteadyGroupNumFn = async () => {
  const params = {
    groupLevel: '1',
    subject: volunteerInfo.value.relSubject,
    searchAllowSubject: volunteerInfo.value.relSubject,
    subjectType: volunteerInfo.value.subjectType,
    recordYear: volunteerInfo.value.defaultYear,
    userScore: volunteerInfo.value.score,
    userMinScore: +volunteerInfo.value.score - 70,
    userMaxScore: +volunteerInfo.value.score + 30,
    localRegionId: volunteerInfo.value.regionId,
    batchType: volunteerInfo.value.batchType,
  };
  const res = await getRushSteadyGroupNum(params);
  if (res.code == 200) {
    if (res.data['10'] > 0) {
      recommendData.value[0].value = res.data['10'];
    }
    if (res.data['20'] > 0) {
      recommendData.value[1].value = res.data['20'];
    }
    if (res.data['30'] > 0) {
      recommendData.value[2].value = res.data['30'];
    }
  }
};

const getClassname = (item) => {
  return item.label === '冲' ? 'red' : item.label === '稳' ? 'orange' : 'green';
};
const echartsData = ref([]);
const visibleData = ref([]);
const getCompetitivenessDataFn = async () => {
  const params = {
    localRegionId: volunteerInfo.value.regionId,
    userScore: volunteerInfo.value.score,
    userMinScore: +volunteerInfo.value.score - 70,
    userMaxScore: +volunteerInfo.value.score + 30,
    recordYear: volunteerInfo.value.searchRankYear,
    subject: volunteerInfo.value.relSubject,
    searchAllowSubject: volunteerInfo.value.relSubject,
    subjectType: volunteerInfo.value.subjectType,
  };
  const res = await competitivenessScore(params);
  if (res.code == 200) {
    rankPercentage.value = res.data.rankPercentage;
    echartsData.value = res.data.scoreNumList.map((item) => {
      return {
        name: item.score,
        value: item.segmentNum,
      };
    });
    visibleData.value = res.data.scoreNumList
      .filter((item) => item.showType == 1)
      .map((item) => item.score);
  }
};

// 合并成一个watch，监听所有相关字段变化
watch(
  () => ({
    regionId: volunteerInfo.value.regionId,
    relSubject: volunteerInfo.value.relSubject,
    score: volunteerInfo.value.score,
    batchType: volunteerInfo.value.batchType,
  }),
  (newVal, oldVal) => {
    // 只有当所有必要字段都有值时才执行
    if (
      newVal.regionId &&
      newVal.relSubject &&
      newVal.score &&
      newVal.batchType
    ) {
      // 检查是否有实际变化
      if (
        !oldVal ||
        newVal.regionId !== oldVal.regionId ||
        newVal.relSubject !== oldVal.relSubject ||
        newVal.score !== oldVal.score ||
        newVal.batchType !== oldVal.batchType
      ) {
        sameScoreListFn();
        getRushSteadyGroupNumFn();
        volunteerPercentageByCityFn();
        volunteerPercentageByMajorFn();
        getCompetitivenessDataFn();
      }
    }
  },
  {
    deep: false, // 不需要deep监听，因为监听的是计算属性
  }
);

onMounted(() => {
  sameScoreListFn();
  getRushSteadyGroupNumFn();
  volunteerPercentageByCityFn();
  volunteerPercentageByMajorFn();
  getCompetitivenessDataFn();
});
</script>

<style scoped lang="scss">
.competitiveness-wrapper {
  border-radius: 16px;
  padding: 30px 28px;
  position: relative;
  background: linear-gradient(
    179deg,
    rgba(255, 255, 255, 0.6) 0%,
    rgba(255, 255, 255, 0.6) 100%
  );
  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    border-radius: 16px;
    padding: 2px;
    background: linear-gradient(
      180deg,
      rgba(255, 255, 255, 1),
      rgba(206, 231, 245, 1)
    );
    -webkit-mask: linear-gradient(#fff 0 0) content-box,
      linear-gradient(#fff 0 0);
    mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
    -webkit-mask-composite: xor;
    mask-composite: exclude;
    pointer-events: none;
  }
  .big-title {
    font-size: 32px;
    font-weight: bold;
    margin-bottom: 16px;
    color: #000;
  }
  .top {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 24px;
    background-color: #fff;
    padding: 28px 22px;
    border-radius: 16px;
    margin-bottom: 12px;
    .rank-wrapper {
      width: 100%;
      .title {
        .text {
          font-size: 24px;
          color: #333;
        }
        .rank {
          font-family: D-DIN-PRO-800-ExtraBold;
          font-size: 30px;
          color: $primary-color;
          margin-left: 5px;
        }
      }
      .analysis-box {
        margin-top: 15px;
        .header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          font-size: 20px;
          margin-bottom: 20px;
          color: #888888;
          .btn {
            padding: 4px 18px;
            background: #e7f4ff;
            border-radius: 6px;
            font-size: 22px;
            color: $primary-color;
            border: 1px solid $primary-color;
          }
        }
        .table {
          :deep(.my-table) {
            th {
              font-weight: normal;
              padding: 6px 24px;
              font-size: 20px;
              border: none;
              color: #777770;
              background: #f0f2f6;
            }
            td {
              padding: 16px 24px;
              font-size: 22px;
              border: none;
              color: #333;
              background: #f7f9fb;
            }
          }
        }
      }
    }
  }

  .bottom {
    background: #fff;
    border-radius: 16px;
    padding: 12px 22px;
    position: relative;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .left {
      .header {
        display: flex;
        align-items: center;
        font-size: 24px;
        color: #000;
        .value {
          font-size: 26px;
          color: $primary-color;
          font-family: D-DIN-PRO-800-ExtraBold;
          margin-left: 10px;
        }
      }
      .content {
        display: flex;
        gap: 30px;
        margin-top: 40px;
        .item {
          text-align: center;
          background: #f7f9fb;
          padding: 16px 32px;
          font-size: 24px;
          border-radius: 10px;
          .label {
            color: #000;
            margin-bottom: 12px;
          }
          .value {
            color: $primary-color;
            font-family: D-DIN-PRO-800-ExtraBold;
            font-size: 28px;
          }
        }
      }
    }
    .right {
      display: flex;
      gap: 62px;
      .content {
        display: block;
        .title {
          font-size: 22px;
          color: #444440;
          margin-bottom: 10px;
          text-align: center;
        }
      }
    }
  }
}
</style>
